<template>
    <div class="main">
      <p  class="main_text">拖车车辆管理</p>
        <!-- ############################################## 查询 ############################################## -->
        <div class="top mb20 p20">
            <el-form :model="inputSearch">
                <div class="df fww">
                    <el-form-item label="车牌号码：" style="width: 20%;">
                        <el-input v-model="inputSearch.carId" placeholder="车牌号码：" class="mr20" />
                    </el-form-item>
                    <el-form-item label="车辆状态：" style="width: 20%;">
                        <el-select v-model="inputSearch.status" placeholder="车辆状态：" class="mr20">
                            <el-option v-for="item in options" :key="item.label" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button type="primary" plain @click="handleReset">重置</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <!-- ############################################## 数据表格 ############################################## -->
        <div class="cyr-flex">
            <div class="mb20">
                <el-button type="primary" v-if="roleList.write" @click="handleAdd">添加拖车</el-button>
            </div>
          <div class="cyr-flex-box" >
            <el-table :data="tableData" :show-overflow-tooltip="true"
                v-adaptive border>
                <el-table-column type="selection" width="55" />
                <el-table-column label="车牌号码" prop="carId"> </el-table-column>
                <el-table-column label="保险有效期">
                    <template #default="props">
                        {{ props.row.insurancePeriod ? formatTime(props.row.insurancePeriod) : '未上传有效期' }}
                    </template>
                </el-table-column>
                <el-table-column label="车辆状态">
                    <template #default="props">
                        <el-tag type="success" v-if="props.row.status === 0">空闲</el-tag>
                        <el-tag type="warning" v-else-if="props.row.status == 1">使用中</el-tag>
                        <el-tag type="danger" v-else-if="props.row.status == 2">维修中</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="props">
                        <el-button size="small" link type="primary" @click="handleView(props.row)"
                            v-if="roleList.write">查看</el-button>
                        <el-button size="small" link type="danger" @click="handleDelete(props.row)"
                            v-if="roleList.write">删除</el-button>
                        <el-button size="small" link type="primary" @click="handleEdit(props.row)"
                            v-if="roleList.write">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- ############################################## 分页 ############################################## -->
            <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
                @change="handleCurrentChange" />
          </div>
        </div>
        <!-- ############################################## 添加司机Dialog ############################################## -->
        <!-- ****************************** 添加拖车 ****************************** -->
        <el-dialog class="dialog" v-model="centerDialogVisible" title="添加拖车" width="40%" align-center
            @close="handleClose">
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">添加拖车</p>
                </div>
            </template>
            <el-form :model="addTableData" ref="ruleFormRef" :rules="rules" label-width="auto" label-position="right"
                class="df fdc aic">
                <el-form-item label="车牌号码：" style="width: 70%;" prop="carId">
                    <el-input v-model="addTableData.carId" :disabled="disabled" />
                </el-form-item>
                <!-- 行驶证上传 -->
                <el-form-item label="行驶证：" style="width: 70%;">
                    <!-- <UploadImages :limit="2" v-if="add" /> -->
                    <upload v-if="add" :limit="1" :multiple="false" :fileType="'image'" ref="uploadImg1"
                        @changeFileList="hanldeDrivingLicense">
                    </upload>
                    <template v-if="view">
                        <el-image style="width: 100px; height: 100px;margin:10px 10px 0 0;"
                            :src="previewDrivingLicenseImg" fit="cover" />
                    </template>
                </el-form-item>
                <el-form-item label="行驶证号：" style="width: 70%;" prop="drivingPermitId">
                    <el-input v-model="addTableData.drivingPermitId" :disabled="disabled" />
                </el-form-item>
                <el-form-item label="保险单：" style="width: 70%;">
                    <!-- <UploadImages :limit="1" v-if="add" /> -->
                    <upload v-if="add" :limit="1" :multiple="false" :fileType="'image'" ref="uploadImg2"
                        @changeFileList="hanldeGuaranteeSlip">
                    </upload>
                    <el-image v-if="view" style="width: 100px; height: 100px" :src="previewInsureImg" fit="cover" />
                </el-form-item>
                <el-form-item label="保险单号：" style="width: 70%;" prop="vehicleInsurance">
                    <el-input v-model="addTableData.vehicleInsurance" :disabled="disabled" />
                </el-form-item>
                <el-form-item label="保险有效期：" style="width: 70%;" prop="insurancePeriod">
                    <el-date-picker v-model="addTableData.insurancePeriod" type="date" @change="handleDateChange"
                        style="width: 100%" :disabled="disabled" value-format="YYYY-MM-DDTHH:mm:ss" />
                </el-form-item>
                <el-form-item label="车辆状态" style="width: 70%;">
                    <el-select v-model="addTableData.status" placeholder="车辆状态：" :disabled="disabled">
                        <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="centerDialogVisible = false">取消</el-button>
                <el-button v-if="add || edit" type="primary" @click="addTableDataBtn(ruleFormRef)">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { RequestTrailerGetlistlimit, RequestAddTrail, RequestTransportDriversList, RequestTrailerDeleteList, RequestBasicVehicleLicenseRecognize } from "@/api/path/index.js";
import { formatTime } from '../../../filters/index'
import { Delete, Download, Plus, ZoomIn, Edit } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { computed, onMounted, ref, } from 'vue';
import upload from '@/components/uploadFile/upload.vue'
import useAuthorize from "@/hooks/authorize";
import UploadImages from '@/components/uploadFile/uploadImages.vue'

let roleList = useAuthorize();
const ruleFormRef = ref<FormInstance>()

const add = ref(false)
const view = ref(false)
const edit = ref(false)
const disabled = ref(false)

//查询条件
const inputSearch = ref<any>({
    carId: '',
    status: '',
})
const options = [
    {
        value: 0,
        label: '空闲',
    },
    {
        value: 1,
        label: '使用中',
    },
    {
        value: 2,
        label: '维修中',
    },
]
const tableData = ref<any[]>([])
const total = ref<number>(0)
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
function getTableData(page: number) {
    RequestTrailerGetlistlimit({
        page: currentPage.value,
        rows: pageSize.value,
        carId: inputSearch.value.carId,
        status: inputSearch.value.status,
        employee: JSON.parse(localStorage.getItem('roleInfo')!)
    }
    ).then((res: any) => {
        tableData.value = res.resultObj.data
        total.value = res.resultObj.total
    })
}
//初始化数据.value
getTableData(currentPage.value)
//当前页数
const handleCurrentChange = (val: number) => {
    getTableData(val)
}
//搜索
const handleSearch = () => {
    currentPage.value = 1
    getTableData(currentPage.value)
}
//搜索重置
const handleReset = () => {
    inputSearch.value.carId = ''
    inputSearch.value.status = ''
    handleSearch()
}

const previewDrivingLicenseImg = ref<string>()//行驶证预览
const previewInsureImg = ref<string>()
//查看
const handleView = (row: any) => {
    addTableData.value = row
    view.value = true
    add.value = false
    edit.value = false
    disabled.value = true
    centerDialogVisible.value = true
    previewDrivingLicenseImg.value = ''
    previewInsureImg.value = ''
    previewDrivingLicenseImg.value = row.img[0].url
    previewInsureImg.value = row.img[1].url
}
//编辑
const handleEdit = (row: any) => {
    addTableData.value = row
    add.value = false
    // view.value = false
    view.value = true
    edit.value = true
    previewDrivingLicenseImg.value = ''
    previewInsureImg.value = ''
    previewDrivingLicenseImg.value = row.img[0].url
    previewInsureImg.value = row.img[1].url
    disabled.value = false
    centerDialogVisible.value = true
}
//删除
const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '您确认删除该数据么？删除后将无法进行恢复!',
        '温馨提示：',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const idsFormData = new FormData()
            idsFormData.append('ids', [row.trailerId])
            RequestTrailerDeleteList(idsFormData).then((data: any) => {
                if (data.code == 0) {
                    ElMessage.success(data.msg)
                    getTableData(currentPage.value)
                } else {
                    ElMessage.error(data.msg)
                }
            })
        })
        .catch(() => {

        })
}
//添加
const centerDialogVisible = ref<boolean>(false)
const handleAdd = () => {
    addTableData.value = {
        carId: '',
        drivingPermitId: '',
        insurancePeriod: '',
        status: 0,
        vehicleInsurance: '',
    }
    add.value = true
    view.value = false
    disabled.value = false
    centerDialogVisible.value = true
}
//添加拖车表单数据
const addTableData = ref<any>({
    carId: '',  //车牌号码
    drivingPermitId: '',//行驶证号
    insurancePeriod: '',//保险有效期
    status: 0,//车辆状态
    vehicleInsurance: '',//保险单号

})
//表单验证规则
const validatecarId = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入车牌号'))
    } else {
        let regex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/
        if (!regex.test(value)) {
            callback(new Error('请输入正确的车牌号'))
        } else {
            callback()
        }
    }
}
const rules = ref<FormRules>({
    carId: {
        type: 'string',
        required: true,
        validator: validatecarId,
        trigger: 'blur'
    },
    drivingPermitId: {
        type: 'string',
        required: true,
        message: '请输入行驶证号',
        trigger: 'blur'
    },
    vehicleInsurance: {
        type: 'string',
        required: true,
        message: '请输入保险单',
        trigger: 'blur'
    },

    insurancePeriod: {
        type: 'date',
        required: true,
        message: '请选择保险有效期',
        trigger: 'change',
    }
})
const addTableDataBtn = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            addTableData.value.companyNode = JSON.parse(localStorage.getItem('roleInfo')!).company
            let addDriverInfo = {
                trailer: addTableData.value,
                vehicleLicense: [drivingImg.value],
                vehicleInsurance: GuaranteeSlipImg.value
            }
            if (edit.value) {
                addDriverInfo.trailerId = addTableData.value.trailerId
                 addDriverInfo.trailer.insurancePeriod =dayjs().format(addTableData.value.insurancePeriod)
                RequestAddTrail(addDriverInfo).then((res: any) => {
                    centerDialogVisible.value = false
                    getTableData(currentPage.value)
                    ElMessage.success(res.msg)
                    drivingImg.value = ''
                    GuaranteeSlipImg.value = ''
                }).catch((err: any) => {
                    ElMessage.error('修改失败')
                })

            } else {
                RequestAddTrail(addDriverInfo).then((res: any) => {
                    console.log(res)
                    ElMessage.success('添加成功')
                    getTableData(currentPage.value)
                    centerDialogVisible.value = false
                    drivingImg.value = ''
                    GuaranteeSlipImg.value = ''
                    formEl.resetFields()
                }).catch((err: any) => {
                    ElMessage.error('添加失败')
                })
            }
        } else {
            ElMessage.error('请填写完整信息')
            return false
        }
    })
}

const drivingImg = ref<string>('')
const GuaranteeSlipImg = ref<string>('')
function fileToBase64(file: Blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve((<string>reader.result).split(',')[1]);
        reader.onerror = (error) => reject(error);
    });
}

const hanldeDrivingLicense = async (fileList: any, flagKey: string) => {
    if (flagKey === 'remove') return drivingImg.value = ''
    drivingImg.value = await fileToBase64(fileList.raw) as string
}
const hanldeGuaranteeSlip = async (fileList: any, flagKey: string) => {
    if (flagKey === 'remove') return GuaranteeSlipImg.value = ''
    GuaranteeSlipImg.value = await fileToBase64(fileList.raw) as string
}
const handleDateChange = (val) => {
    console.log(val)
    let valDate = new Date(val)
    let currentDate = new Date()
    if (val !== null && valDate < currentDate) {
        ElMessage({
            type: 'info',
            message: '有效日期不能小于当前日期'
        })
        addTableData.value.insurancePeriod = ''
        return
    }
}
const uploadImg1 = ref()
const uploadImg2 = ref()
const handleClose = () => {
    // ruleFormRef.value?.resetFields()
    if (add.value) {
        uploadImg1.value.clearFileList()
        uploadImg2.value.clearFileList()
    }
}
</script>

<style lang="scss" scoped>
.main {
    width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
    .top {
        width: 100%;
        background-color: #fff;
    }

    .content {
        width: 100%;
        background-color: #fff;
    }
}

.icon_i {
    position: absolute;
    top: 0;
    bottom: 0;
    left: -6.875rem;
    right: 0;
    margin: auto 0;
}

.downLoad {
    line-height: 1rem;
    margin-left: 0.625rem;
    color: #116cf8;
}

.el-select {
    width: 100%;
}

.el-input-number {
    width: 100%;
}

.drawer_top {
    width: 100%;
    background-color: #fff;
    border-radius: 0.5rem;
}



/* 弹出框样式 */
// ::v-deep .el-overlay {
//     .el-dialog__header {
//         background-color: #116cf8;
//         margin-right: 0;
//     }

//     .el-dialog__title {
//         color: #fff;
//     }

//     .dialog {
//         .el-icon svg {
//             color: #fff;
//         }
//     }

//     .el-button {
//         .el-icon svg {
//             color: #116cf8;
//         }
//     }

//     .el-form {
//         .el-icon svg {
//             color: #dcdfe6;
//         }
//     }
// }
// ::v-deep .el-drawer {
//     .el-overlay .el-icon svg {
//         color: red;
//     }

//     .el-drawer__header {
//         margin-bottom: 0;
//     }
// }

.DocumentNumber {
    .el-button {
        background-color: #fff;
        border: 0.0625rem solid #dcdfe6;
        border-left: none;
    }
}

.drawer_bottom {
    width: 100%;
    height: 10%;
    background-color: #fff;
    padding: 1.25rem;
    position: absolute;
    bottom: 0;
    right: 0;
}

.addTable {
    width: 100%;
    text-align: center;
    height: 2.5rem;
    line-height: 2.5rem;
    background-color: #e7f0fe;
    border: 0.0625rem dotted #116CF8;
    margin-top: 0.375rem;
    color: #116CF8;
    user-select: none;
    cursor: pointer;
}

.upload_img {
    width: 4.875rem;
    height: 4.875rem;
    cursor: pointer;
    user-select: none;
    overflow: hidden;
    border: 0.125rem dotted #dcdfe6;
    border-radius: 0.5rem;
}

.upload_img {
    width: 4.875rem;
    height: 4.875rem;
    cursor: pointer;
    user-select: none;
    overflow: hidden;
    border: 0.125rem dotted #dcdfe6;
    border-radius: 0.5rem;

    .el-icon {
        display: none;
    }
}
</style>
<style lang="scss">
.el-overlay {
    .el-message-box__btns {
        .el-button--primary {
            background: #2E5882;
            border: none;
            color: #fff;
        }
    }
}
</style>